package com.miaostars.myaifriend;

import com.theokanning.openai.completion.chat.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.*;

public class AIHandler {
    private final ConfigManager configManager;
    private final Map<Player, List<ChatMessage>> dialogueHistory = new HashMap<>();

    public AIHandler(ConfigManager configManager) {
        this.configManager = configManager;
    }

    public String getResponse(Player player, String input) {
        FileConfiguration cfg = configManager.getConfig();
        List<ChatMessage> history = dialogueHistory.getOrDefault(player, new ArrayList<>());
        
        // 构建角色设定
        String systemPrompt = String.format(
            "你是%s，背景：%s。玩家是你的%s，你称呼玩家为【%s】，玩家称呼你为【%s】",
            cfg.getString("ai_gender", "助手"),
            cfg.getString("background", "数字生命"),
            cfg.getString("player_relation", "伙伴"),
            cfg.getString("player_title", "旅行者"),
            cfg.getString("creature_title", "向导")
        );
        
        // 更新对话历史
        history.add(new ChatMessage(ChatMessageRole.USER.value(), input));
        if (history.size() > 5) history.remove(0); // 保留最近5条
        
        // 调用OpenAI
        OpenAiService service = new OpenAiService(cfg.getString("openai_api_key"));
        ChatCompletionRequest request = ChatCompletionRequest.builder()
            .model("gpt-3.5-turbo")
            .messages(history)
            .maxTokens(cfg.getInt("max_tokens", 150))
            .temperature(cfg.getDouble("temperature", 0.7))
            .build();
        
        String reply = service.createChatCompletion(request).getChoices().get(0).getMessage().getContent();
        history.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), reply));
        dialogueHistory.put(player, history);
        return reply;
    }
}